package com.gj.demojuc.chap02;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock锁的死锁
 */
public class DeadLockDemoLock {
    private static final Lock lock1 = new ReentrantLock();
    private static final Lock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(()->{
            lock1.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "获得锁1，执行任务");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "等待抢到锁2");
                lock2.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "抢到锁2执行任务");
                } finally {
                    lock2.unlock();
                }
            } finally {
                lock1.unlock();
            }
        },"A").start();

        new Thread(()->{
            lock2.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "获得锁2，执行任务");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "等待抢到锁1");
                lock1.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "抢到锁1执行任务");
                } finally {
                    lock1.unlock();
                }
            } finally {
                lock2.unlock();
            }
        },"B").start();
    }
}
